package com.shuai.baibi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuai.baibi.model.entity.Chart;
import com.shuai.baibi.service.ChartService;
import com.shuai.baibi.mapper.ChartMapper;
import com.shuai.baibi.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @author bxs
 * @description 针对表【chart(帖子)】的数据库操作Service实现
 * @createDate 2023-10-26 14:47:35
 */
@Service
public class ChartServiceImpl extends ServiceImpl<ChartMapper, Chart>
        implements ChartService {

    @Autowired
    private FileService fileService;

    @Override
    public String buildXFAskStr(String goal, String chartType, String csvStr) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("下面是用户上传的原始数据以及分析目标：\n")
                .append("原始数据：\n")
                .append(csvStr)
                .append("\n")
                .append("分析目标：")
                .append(goal);
        if (chartType != null) {
            stringBuilder.append("，用").append(chartType);
        }
        return stringBuilder.toString();
    }

    @Override
    public Map<String, String> processXFResponseData(String responseMessage) {
        if (responseMessage == null) {
            return null;
        }
        HashMap<String, String> resultMap = new HashMap<>();
        int chartDataStartPos = -1;
        int analysisContentStartPos = -1;
        if ((chartDataStartPos = responseMessage.indexOf("result-A:")) == -1
                || (analysisContentStartPos = responseMessage.indexOf("result-B:")) == -1) {
            return null;
        }
        // 二次处理AI生成的ECharts代码
        String genChartData = this.secondCheckUseParenthesisMatching(responseMessage.substring(chartDataStartPos, analysisContentStartPos));
        if (genChartData == null) {
            return resultMap;
        }
        resultMap.put("genChartData", genChartData);
        resultMap.put("genChartResult", responseMessage.substring(analysisContentStartPos + 9));
        return resultMap;
    }

    @Override
    public boolean setExecMessage(Chart chart, String execMessage) {
        chart.setExecMessage(execMessage);
        return this.updateById(chart);
    }

    /**
     * 括号匹配校验AI接口的返回结果
     */
    private String secondCheckUseParenthesisMatching(String content) {
        // 寻找第一个大括号
        int startPos = content.indexOf("{");
        content = content.substring(startPos);
        char[] contentCharacters = content.toCharArray();
        // 括号匹配栈
        Stack<Character> charactersStack = new Stack<>();
        for (int i = 0; i < contentCharacters.length; i++) {
            char contentCharacter = contentCharacters[i];
            if (contentCharacter == '{' || contentCharacter == '(' || contentCharacter == '[') {
                // 入栈
                charactersStack.push(contentCharacter);
            } else if (contentCharacter == '}' || contentCharacter == ')' || contentCharacter == ']') {
                // 匹配出栈
                Character peek = charactersStack.peek();
                if (!peek.equals('{') && contentCharacter == '}'
                        || !peek.equals('[') && contentCharacter == ']'
                        || !peek.equals('(') && contentCharacter == ')') {
                    return null;    // AI返回的代码结果有误
                } else {
                    charactersStack.pop();
                }
            }
            // 如果栈为空了，说明匹配结束。
            if (charactersStack.isEmpty()) {
                content = content.substring(0, i + 1);
                break;
            }
        }
        if (!charactersStack.isEmpty()) {
            return null;
        }
        return content;
    }
}




